package com.colorfruit.admin.business.service.impl;

import com.colorfruit.admin.business.dao.ConfigCommonMapper;
import com.colorfruit.admin.business.dao.GlobalProcessionControlMapper;
import com.colorfruit.admin.business.dao.MediaInfoMapper;
import com.colorfruit.admin.business.service.ConfigService;
import com.colorfruit.admin.business.service.PurchaseService;
import com.colorfruit.admin.pojo.constant.AliConstant;
import com.colorfruit.admin.pojo.constant.CommonConstant;
import com.colorfruit.admin.pojo.constant.RedisConstant;
import com.colorfruit.admin.pojo.entity.ConfigCommon;
import com.colorfruit.admin.pojo.entity.GlobalProcessionControl;
import com.colorfruit.admin.pojo.entity.MediaInfo;
import com.colorfruit.admin.pojo.enums.ErrorCodeEnum;
import com.colorfruit.admin.pojo.enums.GlobalStatusEnum;
import com.colorfruit.framework.common.util.BusinessUtil;
import com.colorfruit.framework.model.admin.CommonDate;
import com.colorfruit.framework.model.pojo.BaseResult;
import com.colorfruit.framework.redis.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Slf4j
@Service
@Transactional
public class ConfigServiceImpl implements ConfigService {

    @Autowired
    GlobalProcessionControlMapper globalProcessionControlMapper; //全局控制状态

    @Autowired
    RedisCache redisCache; //redis缓存

    @Autowired
    ConfigCommonMapper configCommonMapper;//通用配置表

    @Autowired
    PurchaseService purchaseService;

    @Autowired
    MediaInfoMapper mediaInfoMapper;

    @Override
    public GlobalProcessionControl getGlobalProcession() {
        try {
            log.info("[service] [IN] getGlobalProcession param : ");
            GlobalProcessionControl recentProcession = globalProcessionControlMapper.getRecentProcession();
            log.info("[service] [OUT] getGlobalProcession success ");
            return recentProcession;
        }catch (Exception e){
            log.error("# [OUT] errorMessage: " + e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public BaseResult setGlobalProcession(Byte globalStatus) {
        try {
            log.info("[service] [IN] setGlobalProcession param : ");
            GlobalProcessionControl recentProcession = globalProcessionControlMapper.getRecentProcession();
            if (recentProcession == null){
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "当日暂无进度");
            }
            if (globalStatus == recentProcession.getRecordStatus()){ //状态无需变更
                return new BaseResult(ErrorCodeEnum.SUCCESS);
            }else if (globalStatus < recentProcession.getRecordStatus()){ //状态不能往后移动
               return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "无法将进度从后往前调");
            }else {
                //每变更一次精度, 要清除一次缓存
                redisCache.deleteCacheWithPattern(RedisConstant.HOME);
            }
            globalProcessionControlMapper.updateStatus(recentProcession.getId(), globalStatus);
            if (globalStatus == GlobalStatusEnum.PURCHASE.getCode()){
                //从下单阶段往采购阶段变更, 需要做统计处理
                purchaseService.countPurchaseOrder();
            }
            if (globalStatus == GlobalStatusEnum.TRANSPORT.getCode()){
                //计算实际采购价格
                purchaseService.countPurchasePrice();
            }
            log.info("[service] [OUT] setGlobalProcession success ");
            return new BaseResult(ErrorCodeEnum.SUCCESS);
        }catch (Exception e){
            log.error("# [OUT] errorMessage: " + e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public BaseResult setHotSaleProductNums(Integer hotSaleNum) {
        try {
            log.info("[service] [IN] setHotSaleProductNums param : ");
            configCommonMapper.updateConfigWithCode(CommonConstant.HOT_SALE_NUM, hotSaleNum+"");
            log.info("[service] [OUT] setHotSaleProductNums success ");
            return new BaseResult(ErrorCodeEnum.SUCCESS);
        }catch (Exception e){
            log.error("# [OUT] errorMessage: " + e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public BaseResult setTransportCost(String transportCost) {
        try {
            log.info("[service] [IN] setTransportCost param : ");
            configCommonMapper.updateConfigWithCode(CommonConstant.TRANSPORT_COST, transportCost);
            log.info("[service] [OUT] setTransportCost success ");
            return new BaseResult(ErrorCodeEnum.SUCCESS);
        }catch (Exception e){
            log.error("# [OUT] errorMessage: " + e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public BaseResult setDistributionCost(String distributionCost) {
        try {
            log.info("[service] [IN] setDistributionCost param : distributionCost = {}", distributionCost);
            configCommonMapper.updateConfigWithCode(CommonConstant.DISTRIBUTION_COST, distributionCost);
            log.info("[service] [OUT] setDistributionCost success ");
            return new BaseResult(ErrorCodeEnum.SUCCESS);
        }catch (Exception e){
            log.error("# [OUT] errorMessage: " + e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public BaseResult setRedisStatus(String redisStatus) {
        try {
            log.info("[service] [IN] setRedisSelect param : redisStatus = {}", redisStatus);
            configCommonMapper.updateConfigWithCode(CommonConstant.REDIS_STATUS, redisStatus);
            log.info("[service] [OUT] setRedisSelect success ");
            return new BaseResult(ErrorCodeEnum.SUCCESS);
        }catch (Exception e){
            log.error("# [OUT] errorMessage: " + e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public Integer getRedisStatus() {
        try {
            log.info("[service] [IN] getRedisStatus param : ");
            ConfigCommon configCommon = configCommonMapper.getConfigInfoByCode(CommonConstant.REDIS_STATUS);
            String configValue = configCommon.getConfigValue();
            log.info("[service] [OUT] getRedisStatus success ");
            return Integer.parseInt(configValue);
        }catch (Exception e){
            log.error("# [OUT] errorMessage: " + e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public BaseResult restartConfig() {
        log.info("[service] [IN] restartConfig param : ");
        GlobalProcessionControl globalProcessionControl = new GlobalProcessionControl();
        globalProcessionControl.setRecordStatus(GlobalStatusEnum.PRE_PURCHASE.getCode());
        globalProcessionControl.setCreateTime(new Date());
        globalProcessionControlMapper.insert(globalProcessionControl);
        log.info("[service] [OUT] restartConfig success ");
        return new BaseResult(ErrorCodeEnum.SUCCESS);
    }

    @Override
    public BaseResult setStartShopTime(String time) {
        log.info("[service] [IN] setStartShopTime param : ");
        configCommonMapper.updateConfigWithCode(CommonConstant.START_SHOP_TIME, time);
        log.info("[service] [OUT] setStartShopTime success ");
        return new BaseResult(ErrorCodeEnum.SUCCESS);
    }

    @Override
    public BaseResult setStopShopTime(String time) {
        log.info("[service] [IN] setStopShopTime param : ");
        configCommonMapper.updateConfigWithCode(CommonConstant.END_SHOP_TIME, time);
        log.info("[service] [OUT] setStopShopTime success ");
        return new BaseResult(ErrorCodeEnum.SUCCESS);
    }

    @Override
    public BaseResult restartGlobalConfigTime(String time) {
        log.info("[service] [IN] setStopShopTime param : ");
        configCommonMapper.updateConfigWithCode(CommonConstant.RESTART_GLOBAL_TIME, time);
        log.info("[service] [OUT] setStopShopTime success ");
        return new BaseResult(ErrorCodeEnum.SUCCESS);
    }

    @Override
    public BaseResult saveMedia(Byte mediaType, String mediaCode, String ossUrl, Byte forceReplace) {
        log.info("[service] [IN] saveMedia param : mediaType = {}, mediaCode = {}, ossUrl = {}, forceReplace = {}",
                mediaType, mediaCode, ossUrl, forceReplace);
        String mediaUrl = null;
        if (mediaType == (byte)1){
            mediaUrl = AliConstant.DOMAIN + AliConstant.IMAGE + ossUrl;
        }else {
            mediaUrl = AliConstant.DOMAIN + AliConstant.VEDIO + ossUrl;
        }
        MediaInfo mediaInfo = mediaInfoMapper.getMediaByCode(mediaCode);
        if (mediaInfo != null ){
            if (forceReplace == (byte)1){
                mediaInfo.setOssUrl(mediaUrl);
                mediaInfoMapper.updateByPrimaryKeySelective(mediaInfo);
            }else {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), mediaCode + "已存在");
            }
        }else {
            MediaInfo mediaInfoNew = new MediaInfo();
            mediaInfoNew.setMediaCode(mediaCode);
            mediaInfoNew.setOssUrl(mediaUrl);
            mediaInfoNew.setCreateTime(new Date());
            mediaInfoNew.setUpdateTime(new Date());
            mediaInfoMapper.insert(mediaInfo);
        }
        log.info("[service] [OUT] saveMedia success ");
        return new BaseResult(ErrorCodeEnum.SUCCESS);
    }

    @Override
    public BaseResult getMedia(String mediaCode) {
        log.info("[service] [IN] getMedia param : mediaCode = {}", mediaCode);
        MediaInfo mediaInfo = mediaInfoMapper.getMediaByCode(mediaCode);
        log.info("[service] [OUT] getMedia success ");
        return new BaseResult(mediaInfo);
    }


}
